package com.dhcy.mqtt.util;

import cn.hutool.core.util.StrUtil;
import com.google.gson.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommGson {
    private static CommGson commGson;
    private static Gson gson;
    private static JsonParser jsonParser;

    private CommGson() {
    }

    public static CommGson getInstance() {
        if(commGson == null || gson == null) {
            Class var0 = CommGson.class;
            synchronized(CommGson.class) {
                if(commGson == null) {
                    commGson = new CommGson();
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    gsonBuilder.disableHtmlEscaping();
                    //启用驼峰
                    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
                    gson = gsonBuilder.create();
                    jsonParser = new JsonParser();
                }
            }
        }

        return commGson;
    }

    public String toString(Object object) {
        return gson.toJson(object);
    }

    public JsonObject toJsonObject(String json) {
        return jsonParser.parse(json).getAsJsonObject();
    }

    public JsonArray toJsonArray(String json) {
        return jsonParser.parse(json).getAsJsonArray();
    }

    public <T> T toObject(String json, Class<T> t) {
        return gson.fromJson(json, t);
    }

    public  <T> List<T> toList(String json, Class<T> cls) {
        List reList = new ArrayList();
        JsonElement jsonElement = (new JsonParser()).parse(json);
        JsonArray array = jsonElement.getAsJsonArray();
        Iterator iterator = array.iterator();
        Gson gson = new Gson();

        while(iterator.hasNext()) {
            JsonElement json2 = (JsonElement)iterator.next();
            T contact = gson.fromJson(json2, cls);
            reList.add(contact);
        }

        return reList;
    }

    //将json中的key转为驼峰
    public  String jsonToCamelCase(String jsonStr){
        //转换后的字符串
        String str = jsonStr;
        //满足json字符串key的正则
        String regx = "\"\\w+\":";
        //1.将正在表达式封装成对象Patten 类来实现
        Pattern pattern = Pattern.compile(regx);
        //2.将字符串和正则表达式相关联
        Matcher matcher = pattern.matcher(jsonStr);
        //查找符合规则的子串
        while(matcher.find()){
            //取代下划线命名的key为驼峰命名的key
            str = str.replaceFirst(matcher.group(), StrUtil.toCamelCase(matcher.group()));
        }
        return str;
    }
}
